<?php

class CpanelController extends Controller
{
	public $defaultAction = 'index';
	public $layout='menu';
	
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		Yii::app()->params['top'] = 'userManage';
		return CMap::mergeArray(parent::filters(),array(
			'accessControl', // perform access control for CRUD operations
		));
	}
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter. 
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			/*array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('manage','delete','create','update','view','index'),
				'users'=>AdminModule::getAdmins(),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),*/
		);
	}
	/*public function actionManage()
	{
		echo "hiiiiiiiiii";
		exit('here');
	}*/
	/**
	 * Manages all models.
	 */
	public function actionIndex()
	{
		Yii::app()->params['top'] = 'dashboard';
		
		/*$incoming = Orders::model()->findAllByAttributes(array('status'=>'in_cart'));
		$count_incoming = count($incoming);
		
		$successful = Orders::model()->findAllByAttributes(array('status'=>'processed'));;
		$count_successful = count($successful);
		
		$incomplete = Orders::model()->findAllByAttributes(array('status'=>'payment_failure'));;
		$count_incomplete = count($incomplete);
		
		$cancelled = Orders::model()->findAllByAttributes(array('status'=>'cancelled'));;
		$count_cancelled = count($cancelled);
		
		if(isset($_POST['submit']))
		{
			$start_date = $_POST['start_date'];
			$end_date = $_POST['end_date'];
			
			$sql1 = 'SELECT * FROM tbl_orders WHERE status = "in_cart" AND created BETWEEN "'.$start_date.'" AND "'.$end_date.'"';
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql1);
			$incoming = $command->queryAll();
			$count_incoming = count($incoming);
			
			$sql2 = 'SELECT * FROM tbl_orders WHERE status = "processed" AND created BETWEEN "'.$start_date.'" AND "'.$end_date.'"';
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql2);
			$successful = $command->queryAll();
			$count_successful = count($successful);

			$sql3 = 'SELECT * FROM tbl_orders WHERE status = "payment_failure" AND created BETWEEN "'.$start_date.'" AND "'.$end_date.'"';			
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql3);
			$incomplete = $command->queryAll();
			$count_incomplete = count($incomplete);
			
			$sql4 = 'SELECT * FROM tbl_orders WHERE status = "cancelled" AND created BETWEEN "'.$start_date.'" AND "'.$end_date.'"';
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql4);
			$cancelled = $command->queryAll();
			$count_cancelled = count($cancelled);
			
			$this->render('stats', array(
							'count_incoming'=>$count_incoming, 
							'count_successful'=>$count_successful,
							'count_incomplete'=>$count_incomplete,
							'count_cancelled'=>$count_cancelled,
							)
					 ); exit;
		}*/
		
		$this->render('stats');
	
	}
	
	public function actionManage()
	{
		Yii::app()->params['top'] = 'userManage';
		Yii::app()->params['pvt']='manageUser';
		$dataProvider=new CActiveDataProvider('Admin', array(
			'pagination'=>array(
				'pageSize'=>Yii::app()->controller->module->user_page_size,
			),
		));

		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	public function actionManageMembers()
	{
		Yii::app()->params['top'] = 'userManage';
		Yii::app()->params['pvt']='manageUser';
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];

		$this->render('manageMembers',array(
			'model'=>$model,
		));
	
	}

	/**
	 * Displays a particular model.
	 */
	public function actionView()
	{
		$model = $this->loadModel();
		$this->render('view',array(
			'model'=>$model,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		Yii::app()->params['top'] = 'userManage';
		Yii::app()->params['pvt']='createUser';
		$model=new Admin;
		$modelVendor = new Vendor();
		
		if(isset($_POST['Admin']))
		{
			$model->attributes=$_POST['Admin'];
			$model->created=time();
			$model->lastvisit=time();
			$model->role_id = $_POST['Admin']['role_id'];
			if($model->role_id=="2")
			{
				$modelVendor->attributes = $_POST['Vendor'];
				$modelVendor->validate();
				$imageObject=CUploadedFile::getInstance($modelVendor,'vendor_logo_file');
					if (!empty($imageObject))
					{
						$image_name = md5($imageObject->name).'.'.substr($imageObject->type,6); 
						$modelVendor->vendor_logo_file=$image_name;
					}
				
			}
			if($model->validate()) 
			{
				$model->password=Yii::app()->controller->module->encrypting($model->password);
				if($model->save()) {
					if($model->role_id=="2")
					{
					$modelVendor->adminID = $model->adminID;
					if ($modelVendor->validate())
						{
							if (!empty($imageObject))
							{
							$imageObject->saveAs(ApplicationConfig::app()->params['folder_path']['vendorImages'].$image_name);

							$img = Yii::app()->imagemod->load(ApplicationConfig::app()->params['folder_path']['vendorImages'].$image_name);
							if ($img->uploaded) {
						    $img->image_resize          = true;
						    $img->image_ratio_y         = true;
						    $img->image_x               = 100;
						    $img->file_new_name_body = md5($img->file_src_name);
						    $img->process(ApplicationConfig::app()->params['folder_path']['vendorImagesThumb']);
						    if ($img->processed) {
							$modelVendor->vendor_logo_thumb=md5($img->file_src_name).'.'.substr($imageObject->type,6);	
						    } 
							}	
							
							}
							$modelVendor->save();
							
							
							
						}
					}
					$this->redirect(array('manage'));
				}
				
			} 
		}

		$this->render('create',array(
			'model'=>$model,'modelVendor'=>$modelVendor
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadModel();
		$modelVendor = Vendor::model()->getModel('ADMIN-ID',array('adminID'=>$model->adminID));
		if (empty($modelVendor))
		$modelVendor = new Vendor();
		if(isset($_POST['Admin']))
		{
			$model->attributes=$_POST['Admin'];
			if($model->role_id=="2")
				{
					$modelVendor->attributes = $_POST['Vendor'];
					$modelVendor->validate();
					$imageObject=CUploadedFile::getInstance($modelVendor,'vendor_logo_file');
						if (!empty($imageObject))
						{
							$image_name = md5($imageObject->name).'.'.substr($imageObject->type,6); 
							$modelVendor->vendor_logo_file=$image_name;
						}
					
				}
			if($model->validate()) {
				
				
				$old_password = Admin::model()->notsafe()->findByPk($model->adminID);
				if ($old_password->password!=$model->password) {
					$model->password=Yii::app()->controller->module->encrypting($model->password);
					//$model->activkey=Yii::app()->controller->module->encrypting(microtime().$model->password);
				}
				$model->save();
				if($model->role_id=="2")
					{
					$modelVendor->adminID = $model->adminID;
					if ($modelVendor->validate())
						{
							if (!empty($imageObject))
							{
							$imageObject->saveAs(ApplicationConfig::app()->params['folder_path']['vendorImages'].$image_name);
							$img = Yii::app()->imagemod->load(ApplicationConfig::app()->params['folder_path']['vendorImages'].$image_name);
							if ($img->uploaded) {
						    $img->image_resize          = true;
						    $img->image_ratio_y         = true;
						    $img->image_x               = 100;
						    $img->file_new_name_body = md5($img->file_src_name);
						    $img->process(ApplicationConfig::app()->params['folder_path']['vendorImagesThumb']);
						    if ($img->processed) {
							$modelVendor->vendor_logo_thumb=md5($img->file_src_name).'.'.substr($imageObject->type,6);	
						    } 
							}	
							}
							$modelVendor->save();
							$this->redirect(array('manage'));
						}
						
					}
					else 
					$this->redirect(array('manage'));
			} 
		}

		$this->render('update',array(
			'model'=>$model,'modelVendor'=>$modelVendor
			
		));
	}


	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model = $this->loadModel();
			$model->delete();
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_POST['ajax']))
				$this->redirect(array('/admin/cpanel'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=Admin::model()->notsafe()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}
	public function actionError()
	{
		
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}
	
	
}